package dhee.wtqshopproject.controller;

import dhee.wtqshopproject.entity.User;
import dhee.wtqshopproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    // 用户注册
    @PostMapping("/register")
    public ResponseEntity<?> register(@RequestBody User user) {
        try {
            userService.register(user);
            return ResponseEntity.ok(createSuccessResponse("注册成功！"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 用户登录（使用HttpSession存储登录状态）
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody User user, HttpServletRequest request) {
        try {
            User loggedInUser = userService.login(user);

            // 创建会话并存储用户信息
            HttpSession session = request.getSession();
            session.setAttribute("currentUser", loggedInUser);
            session.setAttribute("isLoggedIn", true);

            // 设置会话超时时间为30分钟（1800秒）
            session.setMaxInactiveInterval(1800);

            return ResponseEntity.ok(createSuccessResponse("登录成功", loggedInUser));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 用户退出（清除登录状态）
    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            // 清除会话属性
            session.removeAttribute("currentUser");
            session.removeAttribute("isLoggedIn");
            // 使当前会话失效
            session.invalidate();
        }
        return ResponseEntity.ok(createSuccessResponse("退出成功"));
    }

    // 获取当前登录用户信息
    @GetMapping("/current")
    public ResponseEntity<?> getCurrentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User currentUser = (User) session.getAttribute("currentUser");
            if (currentUser != null) {
                return ResponseEntity.ok(createSuccessResponse("获取当前用户成功", currentUser));
            }
        }
        return ResponseEntity.status(401).body(createErrorResponse("用户未登录"));
    }

    // 删除用户（需要管理员权限）
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteUser(@PathVariable Integer id, HttpServletRequest request) {
        try {
            // 检查当前用户是否是管理员
            if (!isAdmin(request)) {
                return ResponseEntity.status(403).body(createErrorResponse("无权限操作"));
            }

            userService.deleteUser(id);
            return ResponseEntity.ok(createSuccessResponse("用户删除成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 更新用户信息
    @PutMapping
    public ResponseEntity<?> updateUser(@RequestBody User user, HttpServletRequest request) {
        try {
            // 检查当前用户是否有权限更新
            if (!hasPermissionToUpdate(user, request)) {
                return ResponseEntity.status(403).body(createErrorResponse("无权限修改用户信息"));
            }

            userService.updateUser(user);
            return ResponseEntity.ok(createSuccessResponse("用户信息更新成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 根据ID查询用户
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Integer id) {
        try {
            User user = userService.findUserById(id);
            return ResponseEntity.ok(createSuccessResponse("查询成功", user));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 模糊搜索用户
    @GetMapping("/search")
    public ResponseEntity<?> searchUsers(@RequestParam String keyword) {
        try {
            List<User> users = userService.searchUsers(keyword);
            return ResponseEntity.ok(createSuccessResponse("搜索完成", users));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // ===== VIP会员管理接口 =====
    private static final String VIP_ROLE = "vip";
    private static final String ADMIN_ROLE = "admin";

    // 获取所有VIP会员（需要登录）
    @GetMapping("/vip")
    public ResponseEntity<?> getAllVipUsers(HttpServletRequest request) {
        try {
            // 检查登录状态
            if (!isLoggedIn(request)) {
                return ResponseEntity.status(401).body(createErrorResponse("请先登录"));
            }

            List<User> vipUsers = userService.findAllVipUsers();
            return ResponseEntity.ok(createSuccessResponse("获取VIP会员成功", vipUsers));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 升级用户为VIP（需要管理员权限）
    @PutMapping("/vip/upgrade/{id}")
    public ResponseEntity<?> upgradeToVip(@PathVariable Integer id, HttpServletRequest request) {
        try {
            // 检查当前用户是否是管理员
            if (!isAdmin(request)) {
                return ResponseEntity.status(403).body(createErrorResponse("无权限操作"));
            }

            User user = userService.findUserById(id);
            if (user == null) {
                return ResponseEntity.badRequest().body(createErrorResponse("用户不存在"));
            }

            if (VIP_ROLE.equals(user.getRole())) {
                return ResponseEntity.ok(createSuccessResponse("用户已是VIP会员"));
            }

            user.setRole(VIP_ROLE);
            userService.updateUser(user);
            return ResponseEntity.ok(createSuccessResponse("升级VIP会员成功"));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(createErrorResponse(e.getMessage()));
        }
    }

    // 辅助方法：检查用户是否登录
    private boolean isLoggedIn(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        return session != null && session.getAttribute("isLoggedIn") != null;
    }

    // 辅助方法：检查用户是否是管理员
    private boolean isAdmin(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User currentUser = (User) session.getAttribute("currentUser");
            return currentUser != null && ADMIN_ROLE.equals(currentUser.getRole());
        }
        return false;
    }

    // 辅助方法：检查是否有权限更新用户
    private boolean hasPermissionToUpdate(User user, HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            User currentUser = (User) session.getAttribute("currentUser");
            // 管理员可以更新任何用户，普通用户只能更新自己的信息
            return currentUser != null &&
                    (ADMIN_ROLE.equals(currentUser.getRole()) ||
                            currentUser.getUserId().equals(user.getUserId()));
        }
        return false;
    }

    // 统一响应格式方法
    private Map<String, Object> createSuccessResponse(String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", message);
        return response;
    }

    private Map<String, Object> createSuccessResponse(String message, Object data) {
        Map<String, Object> response = createSuccessResponse(message);
        response.put("data", data);
        return response;
    }

    private Map<String, Object> createErrorResponse(String error) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", false);
        response.put("error", error);
        return response;
    }
}